/**
 * 
 */
package com.base.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.base.model.Command;
import com.base.model.SimpleMessage;

/**
 * 
 * @author ricky
 *
 */
public class HelloServerHandler extends SimpleChannelInboundHandler<String>{

	public static Map<String,ChannelHandlerContext> sessionMap = new HashMap<String,ChannelHandlerContext>();
		
	@Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		
		Command command = JSON.parseObject(msg, Command.class);
        
		String bizDomain =command.getAction().substring(0,3);
		if("MSG".endsWith(bizDomain)){
			SimpleMessage simpleMessage = JSON.parseObject(command.getContent(), SimpleMessage.class);
			String targetUserIdStr = simpleMessage.getTargetUsesrId().toString();
			ChannelHandlerContext targetCtx = sessionMap.get(targetUserIdStr);
			//targetCtx.
			
		}else if("LGI".endsWith(bizDomain)){
			sessionMap.put(command.getFromUserId(), ctx);
			ctx.writeAndFlush("Received your login action !\n");
		}else{
			//ctx.writeAndFlush("Received your message !\n");
			System.out.println("not MSG type");
		}
        // 返回客户端消息 - 我已经接收到了你的消息
        
    }
    
	
    /*
     * 
     * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
     * 
     * channelActive 和 channelInActive 在后面的内容中讲述，这里先不做详细的描述
     * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        
        System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");
        
        ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");
        
        super.channelActive(ctx);
    }
}
